const express = require("express");
const userModel = require("../models/user");
const router = express.Router();

/* GET users listing. */
router.get("/", async function (req, res, next) {
  try {
    const users = await userModel.find().select("name -_id").lean();
    res.sendSuccess(users);
  } catch (error) {
    next(error);
  }
});

router.post("/:name?", async function (req, res, next) {
  try {
    const name = req.params.name || "default";
    const user = new userModel({ name: name });
    await user.save();
    res.sendSuccess();
  } catch (error) {
    next(error);
  }
});

router.delete("/:name?", async function (req, res, next) {
  try {
    const name = req.params.name;
    const query = name ? { name: name } : {};
    const user = await userModel.findOneAndDelete(query).sort(name ? {} : { _id: 1 }).exec();
    if (user) {
      res.sendSuccess();
    } else {
      res.sendFailure("User not found", -1);
    }
  } catch (error) {
    next(error);
  }
});

module.exports = router;
